// 云函数入口文件
const cloud = require('wx-server-sdk')
const envId = "daanquanyou-rlnyt"
cloud.init({
    env: envId
})
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
    console.log(event)
    let {
        resultCode,           //SUCCESS/FAIL
        outTradeNo,           //商户订单号
        subOpenid,            //用户的openid      
    } = event

     console.log(outTradeNo)
     //根据订单号获取key
    const getkey =  await db.collection("order")
    .where({
        outTradeNo : outTradeNo,
    })
    .get();
    let key = getkey.data[0].key
    console.log("钥匙",key)
    console.log("用户的openid",subOpenid)
    //把key写入用户的钥匙库里去
    await db.collection('user').doc(subOpenid).update({
                data: {
                    key: _.push(key)
                      }
            })
            .then(res => {
                console.log("钥匙添加成功")
            })
            .catch(error => {
                console.log("error")
            })
  
    // let status = resultCode === "SUCCESS" ? 1 : 2

    // if (status == 1) {
 
    return {
        code: 0,
        msg: 'success',
    }
}